package server.listener;


import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import common.pojo.Constant;
import common.utils.NetUtil;
import common.utils.PropertiesUtil;
import lombok.extern.slf4j.Slf4j;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.server.intf.ServerAioListener;
import server.utils.CacheUtils;

import java.util.Collections;

/**
 * @author gitama
 * @version 1.0
 * @date 2021/5/10 6:13 下午
 */
@Slf4j
public class ProxyServerListener implements ServerAioListener {

    private final String host = PropertiesUtil.getProperty("server.host");

    @Override
    public boolean onHeartbeatTimeout(ChannelContext channelContext, Long interval, int heartbeatTimeoutCount) {
        return false;
    }

    @Override
    public void onAfterConnected(ChannelContext channelContext, boolean isConnected, boolean isReconnect) throws Exception {
        log.debug(channelContext.userid);
    }

    @Override
    public void onAfterDecoded(ChannelContext channelContext, Packet packet, int packetSize) throws Exception {
        log.debug(channelContext.userid);
    }

    @Override
    public void onAfterReceivedBytes(ChannelContext channelContext, int receivedBytes) throws Exception {
        log.debug(channelContext.userid);
    }

    @Override
    public void onAfterSent(ChannelContext channelContext, Packet packet, boolean isSentSuccess) throws Exception {
        log.debug(channelContext.userid);
    }

    @Override
    public void onAfterHandled(ChannelContext channelContext, Packet packet, long cost) throws Exception {
        log.debug(channelContext.userid);
    }

    @Override
    public void onBeforeClose(ChannelContext channelContext, Throwable throwable, String remark, boolean isRemove) throws Exception {
        String key = (String) channelContext.get("host");
        if (StrUtil.isNotBlank(key)) {
            CacheUtils.remove(key);
        }
        String token = (String) channelContext.get("token");
        //根据token下线
        String url = String.format(host + Constant.API_GET_CHANNEL_INFO + "?token=%s", token);
        NetUtil.doPost(url, JSON.toJSONString(Collections.singletonMap("online", "N")));
    }

}
